package com.ty.xiaoyu.service.impl;

import com.ty.xiaoyu.entity.Reply;
import com.ty.xiaoyu.entity.User;
import com.ty.xiaoyu.exception.ReplyOperationException;
import com.ty.xiaoyu.exception.TopicOperationException;
import com.ty.xiaoyu.service.ReplyService;
import com.ty.xiaoyu.util.MyTimeUtil;
import com.ty.xiaoyu.util.RandomIdUtil;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ReplyServiceImpl extends BaseService implements ReplyService {

    @Override
    public List<Reply> getReplyListByTopicId(String topicId) throws ReplyOperationException {
//        List<Reply> replyList = replyMapper.queryReplyListByTopicId(topicId);
//        if (replyList == null || replyList.isEmpty()) {
//            throw new ReplyOperationException("未找到回帖");
//        }
        return replyMapper.queryReplyListByTopicId(topicId);
    }

    @Override
    public Reply addReply(Reply reply) throws ReplyOperationException {
        reply.setReplyId(RandomIdUtil.getId());
        reply.setReplyTime(MyTimeUtil.nowTime());
        reply.setReplyState(1);
        Integer state = replyMapper.insertReply(reply);
        if (state <= 0) {
            throw new ReplyOperationException("新增回复失败");
        }
        User user = userMapper.queryUserById(reply.getUser().getUserId());
        // 更新帖子最后回复信息
        state = topicMapper.updateTopicForLastReply(reply.getTopicId(), reply.getReplyId(), user.getNickname(), reply.getReplyTime());
        if (state <= 0) {
            throw new TopicOperationException("更新帖子最后回复信息失败");
        }
        return reply;
    }

    @Override
    public Reply getReplyById(String replyId) throws ReplyOperationException {
        Reply reply = replyMapper.queryReplyById(replyId);
        if (reply == null) {
            throw new ReplyOperationException("未找到回帖");
        }
        return reply;
    }

    @Override
    public Integer getReplyNum(String topicId) {
        return replyMapper.queryReplyCountByTopicId(topicId);
    }
}
